import gui from '@/lib/gui.js';
import https from '@/lib/https.js';
import config from '@/lib/config.js';
import dateUtil from '@/lib/dateutil.js';

function save(key, value, second){
	uni.setStorageSync(key, value);
	if(second != null){
	  let expiretimestamp = new Date().getTime() + second * 1000;
	  uni.setStorageSync(key + '_timestamp', expiretimestamp);
	}
}

function get(key){
	let expiretimestamp = uni.getStorageSync(key + '_timestamp');
	if(expiretimestamp != null && expiretimestamp != ''){
	  if(expiretimestamp <= new Date().getTime()){
	    uni.removeStorageSync(key + '_timestamp');
	    uni.removeStorageSync(key);
	    return null;
	  }else{
	    return uni.getStorageSync(key);
	  }
	}else{
	  return uni.getStorageSync(key);
	}
}

function remove(key){
	uni.removeStorageSync(key);
}

function saveToken(token){
	save(':token', token)
}

function getToken(){
	var token = this.get(':token');
	if (token == null || token == '') {
	  token = 'dummyUser';
	}
	return token;
}

function isLogined(){
	let token = this.getToken();
	//let userInfo = getUser();
	if (token == null || "" == token || "dummyUser" == token) {
	    return false;
	} else {
	    // if((userInfo.username==null || "" == userInfo.username) && (userInfo.head_img==null || "" == userInfo.head_img)){
	    //   return false
	    // }
		return true;
	}
}

function saveAppBasicConf(appBasicConf) {
  const oneDayTime = 24 * 3600 * 1000;
  save(':appBasicConf', appBasicConf, oneDayTime);
}

function getAppBasicConf() {
  return get(':appBasicConf');
}

function updateAppBasicConf(page, callback){
	if(getAppBasicConf() == null || getAppBasicConf() == ''){
		https.post(page, 'shop/app/loadDict', {version: config.config().Ver}, (res)=>{
			if(res.data.result == 1){
				if (res.data.appBasicConf != null) {
					saveAppBasicConf(res.data.appBasicConf);
					page.appBasicConf=res.data.appBasicConf;
				}
				
				if(callback!=null){
				  callback(getAppBasicConf());
				}
			}else{
				gui.showError(res.data.msg);
			}
		})
	}else{
		page.appBasicConf=getAppBasicConf();
		console.log(page.appBasicConf);
		if(callback!=null){
			callback(getAppBasicConf());
		}
	}
}

function checkLogin(page, callback){
	var that = this;
	if(this.isLogined()){
		if(callback!=null){
			callback();
		}
	}else{
		var loginbox = page.selectComponent('loginbox');
		loginbox.show(page);
		/* updateAppBasicConf(page, ()=>{
			console.log(page);
			
			uni.login({
				provider: "weixin",
				success: function(loginRes){
					console.log(loginRes);
					if(callback!=null){
						callback();
					}
				},
				fail: function(err){
					gui.showError('微信授权登录失败')
				}
			})
		}) */
	}
}

function checkLogin1(callback){
	if(this.isLogined()){
		
	}else{
		// #ifdef APP-PLUS
		uni.preLogin({
			provider: 'univerify',
			success: (res) => {
				console.log("preLogin success: ", res);
				uni.login({
					provider: 'univerify',
					univerifyStyle: {
						'fullScreen': true,
						'backgroundColor': '#fff',
						'icon': {
							'path': '@/static/image/ico-logo.png'
						},
						'closeIcon': {
							'path': '@/static/image/ico-close-black.png'
						},
						'phoneNum': '#666',
						'slogan': '#ccc',
						"authButton": {
							"normalColor": "#33b4ff",
							"highlightColor": "#a2d7f8",  // 授权按钮按下状态背景颜色 默认值：#2861c5（仅ios支持）  
							"disabledColor": "#ccc",  // 授权按钮不可点击时背景颜色 默认值：#73aaf5（仅ios支持）  
							"textColor": "#ffffff",  // 授权按钮文字颜色 默认值：#ffffff  
							"title": "本机号码一键登录", // 授权按钮文案 默认值：“本机号码一键登录”  
							"borderRadius": "24px"	// 授权按钮圆角 默认值："24px" （按钮高度的一半）
						},
						"otherLoginButton": {  
							"visible": true, // 是否显示其他登录按钮，默认值：true  
							"normalColor": "", // 其他登录按钮正常状态背景颜色 默认值：透明 
							"highlightColor": "", // 其他登录按钮按下状态背景颜色 默认值：透明 
							"textColor": "#ccc", // 其他登录按钮文字颜色 默认值：#656565  
							"title": "切换其它号码", // 其他登录方式按钮文字 默认值：“其他登录方式”  
							"borderColor": "",  //边框颜色 默认值：透明（仅iOS支持）  
							"borderRadius": "0px" // 其他登录按钮圆角 默认值："24px" （按钮高度的一半）
						},
						"privacyTerms": {
							"defaultCheckBoxState":true, // 条款勾选框初始状态 默认值： true
							"isCenterHint":false, //未勾选服务条款时点击登录按钮的提示是否居中显示 默认值: false (3.7.13+ 版本支持)
							"uncheckedImage":"", // 可选 条款勾选框未选中状态图片（仅支持本地图片 建议尺寸 24x24px）(3.2.0+ 版本支持)   
							"checkedImage":"", // 可选 条款勾选框选中状态图片（仅支持本地图片 建议尺寸24x24px）(3.2.0+ 版本支持)   
							"checkBoxSize":12, // 可选 条款勾选框大小，仅android支持
							"textColor": "#BBBBBB", // 文字颜色 默认值：#BBBBBB  
							"termsColor": "#5496E3", //  协议文字颜色 默认值： #5496E3  
							"prefix": "我已阅读并同意", // 条款前的文案 默认值：“我已阅读并同意”  
							"suffix": "并使用本机号码登录", // 条款后的文案 默认值：“并使用本机号码登录”  
							"privacyItems": [  // 自定义协议条款，最大支持2个，需要同时设置url和title. 否则不生效  
								{  
									"url": "https://www.baidu.com", // 点击跳转的协议详情页面  
									"title": "用户服务协议" // 协议名称  
								}  
							]  
						}
					},
					success(res){
						console.log(res);
						console.log(res.authResult);
						uniCloud.callFunction({
						  name: 'getPhoneNumber',
						  data: {
						    'access_token': res.authResult.access_token,
						    'uniappopenid': res.authResult.openid
						  }
						}).then(res => {
						  console.log(res);
						  uni.closeAuthView();
						}).catch(err=>{
						  console.log(err);
						  getApp().$gui.showError('手机号授权失败!');
						})
					},
					fail(res){  // 登录失败
						console.log(res)
					}
				})
			},
			fail: (res) => {
				console.log(res);
				this.setUniverifyLogin(false);
				this.setUniverifyErrorMsg(res.errMsg);
				// 失败
				console.log("preLogin fail res: ", res);
			}
		})
		// #endif
	}
}

function saveUser(user){
	save(':userInfo', user);
}

function getUser(){
	return get(':userInfo');
}

function getWeekDate(date){
  let day = (date.getDay()==0?7:date.getDay());
  let onedayTimestamp = 24 * 3600 * 1000;
  let weekFirstDayTimestamp = date.getTime() - (day - 1) * onedayTimestamp;
  let rets = [];
  let weekLabels = dateUtil.getWeekLabels();
  for(let i=0; i<weekLabels.length; i++){
    let weekDay = new Date();
    weekDay.setTime(weekFirstDayTimestamp + i * onedayTimestamp);
    rets[i]=new Object();
    rets[i].date=weekDay;
    rets[i].dateday=weekDay.getDate();
    rets[i].datestr=dateUtil.formatDate(weekDay);
  }
  return rets;
}

export default{
	save,
	get,
	remove,
	saveToken,
	getToken,
	isLogined,
	checkLogin,
	saveUser,
	getUser,
	saveAppBasicConf,
	updateAppBasicConf,
	getAppBasicConf,
	getWeekDate
}
